/*
 * NodeConnectionSentry.java
 *
 * Created on 24 de septiembre de 2006, 01:17 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package guru.merlin.core;

import guru.merlin.server.EPContainer;
import org.apache.log4j.Logger;

/**
 * Esta clase es la centinela de la conexion del nodo.
 * @author sventura
 */
public class NodeConnectionSentry extends Thread{ //MOD SANTIAGO
    static Logger logger = Logger.getLogger(NodeConnectionSentry.class);
    private EPContainer container;
    private boolean running = false;
    
    /** Creates a new instance of NodeConnectionSentry */
    public NodeConnectionSentry(EPContainer container) {
        if (container == null) {
            throw new NullPointerException("The object EPContainer is null");
        }
        this.container = container;
    }//End Constructor
    
    public void run(){//MOD SANTIAGO
        while(container.started){
            this.setRunning(true);
            logger.info(container.route.toString()+ " connected: "+container.ep.isConnected());
            if (!container.ep.isConnected()){//Validamos si el nodo mantiene la conexion 
                //reconectar:
                try {
                    this.container.ep.closeConnection();
                } catch (Exception e2) {
                    logger.warn("can't close connectio; will try to open as next step: "+e2);
                }
                try {
                    logger.info(container.route.toString()+" try to reconnect");
                    this.container.ep.openConnection(container.parametersFilePath);
                    this.container.ep.start();
                } catch (Throwable e) {                   
                    this.printStackTraceByLogger(e);
                }//End try/catch
            }//End if
            try {
                Thread.currentThread().sleep(container.monitoringRound);
            } catch (InterruptedException ex) {
                this.printStackTraceByLogger(ex);
            }//End try/catch/finally
        }//End While
    }//End run    
    
    private void printStackTraceByLogger(Throwable e){
        StringBuffer sb = new StringBuffer();
        StackTraceElement stt[] = e.getStackTrace();
        sb.append("Se genero un: " + e + "\n");
        sb.append("Stacktrace:\n");
        for (int d = 0; d < stt.length; d++) {
            sb.append(stt[d].toString() + "\n");
        }
        logger.error(sb.toString());
    }    

    public boolean isRunning() {
        return running;
    }

    public void setRunning(boolean running) {
        this.running = running;
    }
}
